package com.kkk.shop.back.controller;

import java.io.IOException;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.multipart.MultipartFile;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.kkk.shop.common.controller.BaseController;
import com.kkk.shop.common.util.ConstantFinalUtil;
import com.kkk.shop.common.util.PageInfoUtil;
import com.kkk.shop.goods.pojo.AGoods;
import com.kkk.shop.goods.pojo.AGoodsBrand;
import com.kkk.shop.goods.pojo.AGoodsBrandEnum;
import com.kkk.shop.goods.pojo.AGoodsCate;
/**
 * 处理商品品牌的controller
 * @author kkk
 * */
import com.kkk.shop.goods.service.IGoodsService;
import com.kkk.shop.user.pojo.AAdmins;
@Controller
@RequestMapping("/back/goods/")
public class AGoodsBackController extends BaseController
{
	@Resource
	private IGoodsService goodsService;
	
	/*---------品牌操作开始----------*/
	/**
	 * 处理商品的列表
	 * @param request
	 * @return String
	 * */
	@RequestMapping("/brandList")
	public String brandList(HttpServletRequest request)
	{
		ConstantFinalUtil.loggerMsg.info("---brandList--");
		String keywords=request.getParameter("keywords");
		String status=request.getParameter("status");
		String st=request.getParameter("stDate");
		String ed=request.getParameter("edDate");
		if(keywords==null)
		{
			keywords="";
		}
		keywords=keywords.trim();
		if(status==null)
		{
			status="";
		}
		if(st==null)
		{
			st="";
		}
		if(ed==null)
		{
			ed="";
		}
		Date stDate=null;
		Date edDate=null;
		if(!"".equalsIgnoreCase(st) && !"".equalsIgnoreCase(ed))
		{
			stDate=this.dateFormatUtil.parse(st);
			edDate=this.dateFormatUtil.parse(ed);
		}
		Map<String,Object> paramMap=this.getParamMap();
		paramMap.put("keywords", keywords);
		if(!"".equalsIgnoreCase(status))
		{
			paramMap.put("status", status);
		}
		paramMap.put("stDate", stDate);
		paramMap.put("edDate", edDate);
		//获取分页工具
		PageInfoUtil pageInfoUtil=this.processPageInfo(request);
		//查询对应的商品品牌列表
		List<AGoodsBrand> goodsBrandList=this.goodsService.queryMultiAGoodsBrandService(pageInfoUtil, paramMap);
		
		//将参数放入request作用域中
		request.setAttribute("pageInfoUtil",pageInfoUtil);
		request.setAttribute("goodsBrandList", goodsBrandList);
		
		request.setAttribute("keywords",keywords);
		request.setAttribute("status",status);
		request.setAttribute("st",st);
		request.setAttribute("ed",ed);
		return "/back/goods/brandList";
	}
	
	/**
	 * 品牌添加,首次进入页面
	 * @return 
	 * */
	@RequestMapping("/brandInsert")
	public String brandInsert()
	{
		ConstantFinalUtil.loggerMsg.info("----brandInsert----");
		return "/back/goods/brandInsert";
	}
	
	/**
	 * 品牌添加
	 * @param request
	 * @param goodsBrand
	 * @return String
	 * @throws IOException 
	 * */
	@RequestMapping("/brandInsertSubmit")
	public String brandInsertSubmit(HttpServletRequest request,AGoodsBrand goodsBrand,MultipartFile file) throws IOException
	{
		ConstantFinalUtil.loggerMsg.info("-----brandInsertSubmit------");
		HttpSession session=request.getSession();
		AAdmins admins=(AAdmins) session.getAttribute("admins");
		
		String pubTimeStr=request.getParameter("pubTimeStr");
		goodsBrand.setPubTime(this.dateFormatUtil.parse(pubTimeStr));
		goodsBrand.setAdminsId(admins.getId());
		goodsBrand.setCreateTime(new Date());
		goodsBrand.setUpdateTime(new Date());
		
		Map<String,Object> paramMap=this.getParamMap();
		if(file!=null)
		{
			//注意要使用getOriginalFilename()获取原始文件名称
			paramMap.put("oriFileName",file.getOriginalFilename());
			paramMap.put("inputStream",file.getInputStream());
		}
		JSONObject resultJSON=this.goodsService.insertOneAGoodsBrandService(paramMap,goodsBrand);
		this.info=resultJSON.getString("info");
		request.setAttribute("info",this.info);
		return this.brandInsert();
	}
	
	/**
	 * 品牌更新
	 * @param request
	 * @param bid
	 * @return 
	 * */
	@RequestMapping("/brandUpdate")
	public String brandUpdate(HttpServletRequest request,String bid)
	{
		ConstantFinalUtil.loggerMsg.info("----brandUpdate------");
		Map<String,Object> paramMap=this.getParamMap();
		paramMap.put("id", bid);
		AGoodsBrand goodsBrand=this.goodsService.queryOneAGoodsBrandService(paramMap);
		request.setAttribute("goodsBrand", goodsBrand);
		request.setAttribute("websitePath", ConstantFinalUtil.BUNDLE.getString("website.path"));
		return "/back/goods/brandUpdate";
	}
	
	/**
	 * 品牌更新提交
	 * @param request 
	 * @param bid
	 * @param file
	 * @return String
	 * @throws IOException 
	 * */
	@RequestMapping("/brandUpdateSubmit")
	public String brandUpdateSubmit(HttpServletRequest request,String bid,MultipartFile file) throws IOException
	{
		ConstantFinalUtil.loggerMsg.info("------brandUpdateSubmit--------");
		Map<String,Object> paramMap=this.getParamMap();
		paramMap.put("id",bid);
		AGoodsBrand goodsBrand=this.goodsService.queryOneAGoodsBrandService(paramMap);
		request.setAttribute("goodsBrand", goodsBrand);
		String pubTimeStr=request.getParameter("pubTimeStr");
		goodsBrand.setPubTime(this.dateFormatUtil.parse(pubTimeStr));
		
		String name = request.getParameter("name");
		String website = request.getParameter("website");
		String content = request.getParameter("content");
		String status = request.getParameter("status");
		
		goodsBrand.setName(name);
		goodsBrand.setWebsite(website);
		goodsBrand.setContent(content);
		goodsBrand.setStatus(Byte.valueOf(status));
		goodsBrand.setUpdateTime(new Date());
		
		paramMap=this.getParamMap();
		if(file!=null)
		{
			paramMap.put("oriFileName", file.getOriginalFilename());
			paramMap.put("inputStream", file.getInputStream());
		}
		JSONObject resultJSON=this.goodsService.updateOneAGoodsBrandService(paramMap,goodsBrand);
		this.info=resultJSON.getString("info");
		request.setAttribute("info", this.info);
		return this.brandUpdate(request, bid);
	}
	/*---------品牌操作开始----------*/
	
	/*---------分类操作开始----------*/
	/**
	 * 分类列表操作
	 * @param request
	 * @return String
	 * */
	@RequestMapping("/cateList")
	public String cateList(HttpServletRequest request)
	{
		ConstantFinalUtil.loggerMsg.info("-----cateList---");
		//设置搜索条件
		String keywords=request.getParameter("keywords");
		String status=request.getParameter("status");
		String st=request.getParameter("st");
		String ed=request.getParameter("ed");
		if(keywords==null)
		{
			keywords="";
		}
		keywords=keywords.trim();
		if(status==null)
		{
			status="";
		}
		if(st==null)
		{
			st="";
		}
		if(ed==null)
		{
			ed="";
		}
		Date stDate=null;
		Date edDate=null;
		if(!"".equalsIgnoreCase(st)&&!"".equalsIgnoreCase(ed))
		{
			stDate=this.dateFormatUtil.parse(st);
			edDate=this.dateFormatUtil.parse(ed);
		}
		Map<String,Object> paramMap=this.getParamMap();
		paramMap.put("keywords", keywords);
		if(!"".equalsIgnoreCase(status))
		{
			paramMap.put("status", status);
		}
		paramMap.put("stDate", stDate);
		paramMap.put("edDate", edDate);
		//处理分页工具类
		PageInfoUtil pageInfoUtil=this.processPageInfo(request);
		List<AGoodsCate> cateList=this.goodsService.queryMultiGoodsCateService(pageInfoUtil, paramMap);
		
		//将信息设置到作用域中方便前台jsp使用
		request.setAttribute("cateList", cateList);
		request.setAttribute("pageInfoUtil",pageInfoUtil);
		request.setAttribute("keywords",keywords);
		request.setAttribute("status",status);
		request.setAttribute("st", st);
		request.setAttribute("ed", ed);
		return "/back/goods/cateList";
	}
	/**
	 * 分类添加
	 * @return
	 * */
	@RequestMapping("/cateInsert")
	public String cateInsert()
	{
		ConstantFinalUtil.loggerMsg.info("------cateInsert-------");
		return "/back/goods/cateInsert";
	}
	/**
	 * 分类添加提交
	 * @param request
	 * @param goodsCate
	 * @param file
	 * @return
	 * */
	@RequestMapping("/cateInsertSubmit")
	public String cateInsertSubmit(HttpServletRequest request,AGoodsCate goodsCate,MultipartFile file)
	{
		ConstantFinalUtil.loggerMsg.info("-------cateInsertSubmit-------");
		HttpSession session=request.getSession();
		AAdmins admins=(AAdmins) session.getAttribute("admins");
		
		String pubTimeStr=request.getParameter("pubTimeStr");
		goodsCate.setPubTime(this.dateFormatUtil.parse(pubTimeStr));
		goodsCate.setAdminsId(admins.getId());
		goodsCate.setCreateTime(new Date());
		goodsCate.setUpdateTime(new Date());
		
		JSONObject resultJSON=this.goodsService.insertOneGoodsCateService(goodsCate);
		this.info=resultJSON.getString("info");
		request.setAttribute("info", this.info);
		return this.cateInsert();
	}
	
	/**
	 * 分类更新 
	 * @param request
	 * @param cid,从上一个页面获取id然互查询出对应的信息
	 * @return 
	 **/
	@RequestMapping("/cateUpdate")
	public String cateUpdate(HttpServletRequest request,String cid)
	{
		ConstantFinalUtil.loggerMsg.info("-------cateUpdate-------");
		Map<String,Object> paramMap=this.getParamMap();
		paramMap.put("id", cid);
		AGoodsCate goodsCate=this.goodsService.queryOneGoodsCateService(paramMap);
		request.setAttribute("goodsCate",goodsCate);
		return "/back/goods/cateUpdate";
	}
	
	/**
	 * 分类更新提交
	 * @param request
	 * @param cid
	 * @param file
	 * @return
	 * */
	@RequestMapping("/cateUpdateSubmit")
	public String cateUpdateSubmit(HttpServletRequest request,String cid,MultipartFile file)
	{
		ConstantFinalUtil.loggerMsg.info("-----cateUpdateSubmit-------");
		Map<String,Object> paramMap=this.getParamMap();
		paramMap.put("id", cid);
		AGoodsCate goodsCate=this.goodsService.queryOneGoodsCateService(paramMap);;
		request.setAttribute("goodsCate", goodsCate);
		String pubTimeStr = request.getParameter("pubTimeStr");
		goodsCate.setPubTime(this.dateFormatUtil.parse(pubTimeStr));
		
		String name = request.getParameter("name");
		String url = request.getParameter("url");
		String spec = request.getParameter("spec");
		String content = request.getParameter("content");
		String status = request.getParameter("status");
		
		goodsCate.setName(name);
		goodsCate.setUrl(url);
		goodsCate.setContent(content);
		goodsCate.setSpec(spec);
		goodsCate.setStatus(Byte.valueOf(status));
		
		goodsCate.setUpdateTime(new Date());
		
		JSONObject resDBJSON = this.goodsService.updateOneGoodsCateService(goodsCate);
		this.info = resDBJSON.getString("info");
		request.setAttribute("info", info);
		return this.cateUpdate(request, cid);
	}
	/*-------分类操作结束------*/
	
	/*-------商品操作开始------*/
	/**
	 * @param request
	 * @return String
	 * */
	@RequestMapping("/goodsList")
	public String goodsList(HttpServletRequest request)
	{
		//设置搜索条件
		String keywords=request.getParameter("keywords");
		String status=request.getParameter("status");
		String st=request.getParameter("st");
		String ed=request.getParameter("ed");
		if(keywords==null)
		{
			keywords="";
		}
		keywords=keywords.trim();
		if(status==null)
		{
			status="";
		}
		if(st==null)
		{
			st="";
		}
		if(ed==null)
		{
			ed="";
		}
		Date stDate=null;
		Date edDate=null;
		if(!"".equalsIgnoreCase(st)&&!"".equalsIgnoreCase(ed))
		{
			stDate=this.dateFormatUtil.parse(st);
			edDate=this.dateFormatUtil.parse(ed);
		}
		Map<String,Object> paramMap=this.getParamMap();
		paramMap.put("keywords", keywords);
		if(!"".equalsIgnoreCase(status))
		{
			paramMap.put("status", status);
		}
		paramMap.put("stDate", stDate);
		paramMap.put("edDate", edDate);
		//处理分页工具类
		PageInfoUtil pageInfoUtil=this.processPageInfo(request);
		List<AGoods> goodsList=this.goodsService.queryMultiGoodsService(pageInfoUtil, paramMap);
		
		//将信息设置到作用域中方便前台jsp使用
		request.setAttribute("goodsList", goodsList);
		request.setAttribute("pageInfoUtil",pageInfoUtil);
		request.setAttribute("websitePath", ConstantFinalUtil.BUNDLE.getString("website.path"));
		
		request.setAttribute("keywords",keywords);
		request.setAttribute("status",status);
		request.setAttribute("st", st);
		request.setAttribute("ed", ed);
		return "/back/goods/goodsList";
	}
	
	/**
	 * 商品插入
	 * @param request
	 * @return String
	 * */
	@RequestMapping("/goodsInsert")
	public String goodsInsert(HttpServletRequest request)
	{
		ConstantFinalUtil.loggerMsg.info("-------goodsInsert-------");
		Map<String,Object> paramMap=this.getParamMap();
		paramMap.put("status",AGoodsBrandEnum.STATUS_ENABLE.getStatus());
		List<AGoodsBrand> goodsBrandList=this.goodsService.queryMultiAGoodsBrandService(null, paramMap);
		paramMap=this.getParamMap();
		paramMap.put("parentId","0");
		List<AGoodsCate> goodsCateList=this.goodsService.queryMultiGoodsCateService(null, paramMap);
		JSONArray goodsTreeArr=	this.goodsService.queryTreeGoodsCateService(goodsCateList, request.getContextPath());
		request.setAttribute("goodsBrandList",goodsBrandList);
		request.setAttribute("goodsCateList",goodsCateList);
		request.setAttribute("goodsTreeArr",goodsTreeArr);
		return "/back/goods/goodsInsert";
	}
	/**
	 * 商品插入提交
	 * @param request
	 * @param goodsCate
	 * @param file
	 * @throws IOException 
	 * @retun String
	 * */
	@RequestMapping("/goodsInsertSubmit")
	public String goodsInsertSubmit(HttpServletRequest request,AGoods goods,MultipartFile file) throws IOException
	{
		ConstantFinalUtil.loggerMsg.info("------cateInsertSubmit-------");
		HttpSession session=request.getSession();
		AAdmins admins=(AAdmins) session.getAttribute("admins");
		String pubTimeStr=request.getParameter("pubTimeStr");
		goods.setPubTime(this.dateFormatUtil.parse(pubTimeStr));
		
		//拼装规格
		JSONArray specArr=new JSONArray();
		Map<String,String[]> paramReqMap=request.getParameterMap();
		for (Iterator iterator = paramReqMap.entrySet().iterator(); iterator.hasNext();)
		{
			Entry me=(Entry) iterator.next();
			String key=me.getKey()+"";
			String[] value=(String[]) me.getValue();
			if(key.startsWith("spec_name"))
			{
				//处理规格头
				JSONObject json=new JSONObject();
				json.put("name", value[0]);
				String count=key.substring(key.lastIndexOf("_")+1,key.length());
				json.put("count",count);
				specArr.add(json);
			}
		}
		/* 取出键
		 * [
				{
					"name": "主体",
					"keys": [
					{
						"name":"系列",
						"value":"T 系列"
					},
					{
						"name":"型号",
						"value":"ThinkPad T460"
					}]
				}
			]
		 *  */
		//循环出对应的键
		for(Iterator iterator=specArr.iterator();iterator.hasNext();)
		{
			//由于之前存的是json数据,因此取出的是JSONObject
			JSONObject json=(JSONObject) iterator.next();
			String count=json.getString("count");
			
			//取出所有的键
			String[] keys=request.getParameterValues("spec_key_"+count);
			String[] values=request.getParameterValues("spec_key_"+count);
			JSONArray keysArr=new JSONArray();
			for(int i=0;i<keys.length;i++)
			{
				String key=keys[i];
				JSONObject keysJSON=new JSONObject();
				keysJSON.put("name", key);
				keysJSON.put("value",values[i]);
				keysArr.add(keysJSON);
			}
			json.put("keys", keysArr);
		}
		//存入到数据库中以json数据串形式
		goods.setSpec(specArr.toJSONString());
		//将管理的员id作为商品的关联的外键
		goods.setAdminsId(admins.getId());
		goods.setUpdateTime(new Date());
		goods.setCreateTime(new Date());
		
		Map<String,Object> paramMap=this.getParamMap();
		//对图片文件进行处理
		if(file!=null)
		{
			paramMap.put("oriFileName",file.getOriginalFilename());
			paramMap.put("inputStream",file.getInputStream());
		}
		JSONObject resDBJSON=this.goodsService.insertOneGoodsService(paramMap,goods);
		this.info=resDBJSON.getString("info");
		request.setAttribute("info",info);
		return this.goodsInsert(request);
	}
	
	/**
	 * 商品更新
	 * @param request
	 * @param gid
	 * @return 
	 * */
	@RequestMapping("/goodsUpdate")
	public String goodsUpdate(HttpServletRequest request,String gid)
	{
		ConstantFinalUtil.loggerMsg.info("-----goodsUpdate----");
		//先查询对应的信息
		Map<String,Object> paramMap=this.getParamMap();
		paramMap.put("id", gid);
		//查询数据库
		AGoods goods =this.goodsService.queryOneGoodsService(paramMap);
		//存储商品到作用域
		request.setAttribute("goods",goods);
		
		paramMap=this.getParamMap();
		paramMap.put("status",AGoodsBrandEnum.STATUS_ENABLE.getStatus());
		List<AGoodsBrand> goodsBrandsList=this.goodsService.queryMultiAGoodsBrandService(null, paramMap);
		//查询所有的分类
		paramMap=this.getParamMap();
		paramMap.put("parentId","0");
		List<AGoodsCate> goodsCateList=this.goodsService.queryMultiGoodsCateService(null, paramMap);
		JSONArray goodsCateTreeArr=this.goodsService.queryTreeGoodsCateService(goodsCateList, request.getContextPath());
		request.setAttribute("goodsCateTreeArr",goodsCateTreeArr);
		request.setAttribute("goodsBrandsList", goodsBrandsList);
		request.setAttribute("goodsCateList",goodsCateList);
		request.setAttribute("websitePath",ConstantFinalUtil.BUNDLE.getString("website.path"));
		return "/back/goods/goodsUpdate";
	}
	
	/**
	 * 商品更新提交
	 * @param request
	 * @param gid
	 * @param file
	 * @return
	 * @throws IOException 
	 * */
	@RequestMapping("/goodsUpdateSubmit")
	public String goodsUpdateSubmit(HttpServletRequest request,String gid,MultipartFile file) throws IOException
	{
		ConstantFinalUtil.loggerMsg.info("-----goodsUpdateSubmit-----");
		Map<String,Object>paramMap=this.getParamMap();
		paramMap.put("id",gid);
		AGoods goods=this.goodsService.queryOneGoodsService(paramMap);
		request.setAttribute("goods",goods);

		String pubTimeStr=request.getParameter("pubTimeStr");
		goods.setPubTime(this.dateFormatUtil.parse(pubTimeStr));
		
		String cateId = request.getParameter("cateId");
		String brandId = request.getParameter("brandId");
		String name = request.getParameter("name");
		String title = request.getParameter("title");
		String url = request.getParameter("url");
		String weight = request.getParameter("weight");
		String remainNum = request.getParameter("remainNum");
		String marketPrice = request.getParameter("marketPrice");
		String price = request.getParameter("price");
		String content = request.getParameter("content");
		String status = request.getParameter("status");
		
		goods.setCateId(Integer.valueOf(cateId));
		goods.setBrandId(Integer.valueOf(brandId));
		goods.setName(name);
		goods.setTitle(title);
		goods.setUrl(url);
		goods.setWeight(Double.valueOf(weight));
		goods.setRemainNum(Integer.valueOf(remainNum));
		goods.setMarketPrice(Double.valueOf(marketPrice));
		goods.setPrice(Double.valueOf(price));
		goods.setContent(content);
		goods.setStatus(Byte.valueOf(status));
		
		//拼装规格
		JSONArray specArr=new JSONArray();
		Map<String,String[]> paramReqMap=request.getParameterMap();
		for(Iterator it=paramReqMap.entrySet().iterator();it.hasNext();)
		{
			Entry me=(Entry) it.next();
			String key=me.getKey()+"";
			String[] values=(String[]) me.getValue();
			if(key.startsWith("spec_name"))
			{
				/**
				 * 主体,处理器,内存
				 * spec_name_1,求出最后一个数字
				 * */
				JSONObject json=new JSONObject();
				json.put("name",values[0]);
				String count=key.substring(key.lastIndexOf(".")+1,key.length());
				json.put("count",count);
				specArr.add(json);
			}
		}
		/* 取出键
		 * [
				{
					"name": "主体",
					"keys": [
					{
						"name":"系列",
						"value":"T 系列"
					},
					{
						"name":"型号",
						"value":"ThinkPad T460"
					}]
				}
			]
		 *  */
		for(Iterator it=specArr.iterator();it.hasNext();)
		{
			JSONObject json=(JSONObject) it.next();
			//将得到的数字取出,用于拼接
			String count=json.getString("count");
			//取出所有的键
			String[] keys=request.getParameterValues("spec_key_"+count);
			String[] values=request.getParameterValues("spec_value_"+count);
			
			JSONArray keysArr=new JSONArray();
			for(int i=0;i<keys.length;i++)
			{
				String key=keys[i];
				JSONObject keysJSON=new JSONObject();
				keysJSON.put("name",key);
				keysJSON.put("value", values[i]);
				keysArr.add(keysJSON);
			}
			json.put("keys",keysArr);
		}
		if(specArr.size()>0)
		{
			goods.setSpec(specArr.toJSONString());
		}
		goods.setUpdateTime(new Date());
		paramMap=this.getParamMap();
		if(file!=null)
		{
			paramMap.put("oriFileName",file.getOriginalFilename());
			paramMap.put("inputStream",file.getInputStream());
		}
		JSONObject resDBJSON=this.goodsService.updateOneGoodsService(goods);
		this.info=resDBJSON.getString("info");
		request.setAttribute("info",this.info);
		//将gid传入更新页面,查询对应的goods信息
		return this.goodsUpdate(request, gid);
	}
	/**
	 * 分类列表
	 * @param request
	 * */
	@RequestMapping("/cateTreeList")
	public String cateTreeList(HttpServletRequest request)
	{
		ConstantFinalUtil.loggerMsg.info("------cateTreeList-----");
		Map<String,Object> paramMap=this.getParamMap();
		//查询对应的所有父级元素
		paramMap=this.getParamMap();
		paramMap.put("parentId","0");
		List<AGoodsCate> goodsCateList=this.goodsService.queryMultiGoodsCateService(null,paramMap);
		//rootPath为项目的路径
		JSONArray goodsCateTreeArr=this.goodsService.queryTreeGoodsCateService(goodsCateList, request.getContextPath());
		request.setAttribute("goodsCateTreeArr", goodsCateTreeArr);
		return "/back/goods/cateTreeList";
	}
	/*-------商品操作结束------*/
	
}
